<?php

namespace App\Api\Dao;

use App\Exceptions\DaoException;
use App\Helpers\Lib\WechatPay;
use App\Helpers\ResponseEnum;
use App\Models\TongUser;
use App\Models\TongUserRecharge;

class UserRechargeDao extends BaseDao
{

    /**
     * 查询构造器
     * @param $data
     * @return \Illuminate\Database\Eloquent\Builder
     */
    function getBuildQuery($data)
    {
        // TODO: Implement getBuildQuery() method.
        $query = TongUserRecharge::query();
        //id 查询
        if(checkIsHasField($data,'id')){
            $query->where('id',$data['id']);
        }
        //查询状态
        if(checkIsHasField($data,'status')){
            $query->where('status',$data['status']);
        }
        //根据用户id查询
        if(checkIsHasField($data,'u_id')){
            $query->where('u_id',$data['u_id']);
        }
        return $query;
    }

    /**
     * 创建用户户的充值定安
     * @param array $data
     * @return array
     */
    public function createUserRecharge(array $data)
    {
        //dd($data);
        //获取用户信息
        $user_info = TongUser::query()->where('id',$data['u_id'])->first();
        $data['order_no'] = 'C'.makeOrderNo();
        $result = TongUserRecharge::query()->create($data);
        if(!$result){
            throw new DaoException(ResponseEnum::HTTP_ERROR,'创建失败');
        }
        //dd($user_info);
        $result = (new WechatPay())->to_pay([
            'order_no'=>$data['order_no'],
            'description'=>'钱包充值',
            'openid'=>$user_info['openid'],
            'order_price'=>$data['money'],
            'pay_price'=>$data['money']
        ],[
            'notify_url'=>'https://dztxsother.19w.top/api/wechat_pay_recharge_notice'
        ]);
        return $result;
    }

    /**
     *获取充值订单详情
     * @param array $data
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|void
     */
    public function getUserRechargeInfo(array $data)
    {
        return $this->getBuildQuery($data)->first();
    }
}
